﻿using System.Collections.Generic;
using BackTask.Core.Extensions;
using BackTask.Model;
using Quartz;
using Quartz.Impl;

namespace BackTask.Core.Builders
{
    public sealed class TaskJobBuilder : BaseTaskJobBuilder
    {
        private BackTaskConfiguration configuration;
        private BackTaskSettingConfiguration taskSettingConfiguration;
        private IScheduler scheduler;

        public override TaskJobBuilder UseTaskConfiguration(BackTaskConfiguration configuration)
        {
            this.configuration = configuration;

            return this;
        }

        public override BackTaskConfiguration GetTaskConfiguration()
        {
            return this.configuration;
        }

        public override BackTaskSettingConfiguration GetTaskSettingConfiguration()
        {
            return this.taskSettingConfiguration;
        }

        public override TaskJobBuilder UseTaskSettingConfiguration(BackTaskSettingConfiguration taskSettingConfiguration)
        {
            this.taskSettingConfiguration = taskSettingConfiguration;

            return this;
        }

        public override TaskJobBuilder Build()
        {
            if (this.configuration == null) throw new System.ArgumentNullException("no configuration support");
            this.configuration.BuildConfiguration();
            IEnumerable<TaskJob> jobs = this.configuration.BindJobs();
            this.scheduler = this.BuildJobs(jobs);
            return this;
        }

        public override void Start()
        {
            this.scheduler.Start();
            if (this.taskSettingConfiguration != null)
            {
                this.taskSettingConfiguration.Run();
            }
        }

        public override IScheduler GetScheduler()
        {
            return this.scheduler;
        }

        private void InitScheduler()
        {
            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = factory.GetScheduler().Result;
            this.scheduler = scheduler;
        }

        private IScheduler BuildJobs(IEnumerable<TaskJob> taskJobs)
        {
            InitScheduler();
            foreach (var taskJob in taskJobs)
            {
                scheduler.AddTaskJob(taskJob);
            }

            return scheduler;
        }
    }
}
